package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketTopic;
import com.cskaoyan.market.service.AdminTopicService;
import com.cskaoyan.market.service.impl.AdminTopicServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.cskaoyan.market.vo.MarketTopicVo;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 专题管理
 * @author Meltedicecream
 * @since 2023/06/21 20:18
 */
@WebServlet("/admin/topic/*")
public class AdminTopicController extends HttpServlet {

    private AdminTopicService topicService = new AdminTopicServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/topic/", "");
        if ("list".equals(op)){
            list(req,resp);
        }
        if ("read".equals(op)){
            read(req,resp);
        }
    }

    /**
     * TODO:read方法有问题，可能是Vo响应格式不对
     * @param req
     * @param resp
     * @throws IOException
     */
    private void read(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idParam = req.getParameter("id");
        Integer id = Integer.parseInt(idParam);
        MarketTopic marketTopic = topicService.read(id);
        if (marketTopic == null){
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        MarketTopicVo marketTopicVo = new MarketTopicVo();
        //TODO:此处的goodsList赋值不确定
        marketTopicVo.setGoodsList(new ArrayList<>());
        marketTopicVo.setTopic(marketTopic);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketTopicVo)));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/topic/", "");
        if ("create".equals(op)){
            create(req,resp);
        }
        if ("delete".equals(op)){
            delete(req,resp);
        }
        if ("update".equals(op)){
            update(req,resp);
        }
    }

    /**
     * 修改专题
     * @param req
     * @param resp
     */
    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        Integer id = JacksonUtil.parseInteger(reqBody, "id");
        String title = JacksonUtil.parseString(reqBody, "title");
        String subtitle = JacksonUtil.parseString(reqBody, "subtitle");
        BigDecimal price = JacksonUtil.parseObject(reqBody, "price", BigDecimal.class);
        String readCount = JacksonUtil.parseString(reqBody, "readCount");
        String picUrl = JacksonUtil.parseString(reqBody, "picUrl");
        Integer sortOrder = JacksonUtil.parseInteger(reqBody, "sortOrder");
        List<Integer> goodList = JacksonUtil.parseIntegerList(reqBody, "goods");
        if (goodList == null){
            goodList = new ArrayList<>();
        }
        Integer[] goods = new Integer[goodList.size()];
        for (int i = 0; i < goodList.size(); i++) {
            goods[i] = goodList.get(i);
        }
        LocalDateTime addTime = JacksonUtil.parseObject(reqBody, "addTime", LocalDateTime.class);
        LocalDateTime updateTime = JacksonUtil.parseObject(reqBody, "updateTime", LocalDateTime.class);
        String content = JacksonUtil.parseString(reqBody, "content");
        //TODO:如果price不是数字没有判断
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(subtitle) || price == null){
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        MarketTopic marketTopic = topicService.update(id,title,subtitle,price,readCount,picUrl,goods,content,sortOrder,addTime,updateTime);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketTopic)));

    }

    /**
     * 删除专题
     * @param req
     * @param resp
     */
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        Integer id = JacksonUtil.parseInteger(reqBody,"id");
        if (id == null){
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        topicService.delete(id);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok()));

    }

    /**
     * 新建专题
     * @param req
     * @param resp
     */
    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        BufferedReader reader = req.getReader();
        String reqBody = reader.readLine();
        //获取参数
        String title = JacksonUtil.parseString(reqBody, "title");
        String subtitle = JacksonUtil.parseString(reqBody, "subtitle");
        BigDecimal price = JacksonUtil.parseObject(reqBody, "price", BigDecimal.class);
        String readCount = JacksonUtil.parseString(reqBody, "readCount");
        String picUrl = JacksonUtil.parseString(reqBody, "picUrl");
        List<Integer> goodList = JacksonUtil.parseIntegerList(reqBody, "goods");
        if (goodList == null){
            goodList = new ArrayList<Integer>();
        }
        Integer[] goods = new Integer[goodList.size()];
        for (int i = 0; i < goodList.size(); i++) {
            goods[i] = goodList.get(i);
        }
        String content = JacksonUtil.parseString(reqBody, "content");
        //判断参数合法性
        //TODO:如果price不是数字没有判断
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(subtitle) || price == null){
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
            return;
        }
        MarketTopic marketTopic = topicService.create(title,subtitle,price,readCount,picUrl,goods,content);
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.ok(marketTopic)));
    }

    /**
     * 专题管理首页展示及查询
     * @param req
     * @param resp
     */
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求参数（请求行上的参数好像加密了，请求体参数正常，选择从请求体获取）
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String title = req.getParameter("title");
        String subtitle = req.getParameter("subtitle");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        //验证参数合法性
        Integer page = null;
        Integer limit = null;
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.badArgument()));
        }

        //调用service方法返回一个List<MarketTopic>
        List<MarketTopic> marketTopicList = topicService.list(page,limit,title,subtitle,sort,order);
        //响应
        resp.getWriter().println(JacksonUtil.writeValueAsString(ResponseUtil.okList(marketTopicList)));

    }
}
